package com.mall.service.user;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mall.client.user.SessService;
import com.mall.custom.dao.read.SessReadMapper;
import com.mall.custom.dao.write.SessWriteMapper;
import com.mall.pojo.Sess;
import com.mall.pojo.SessExample;
import com.mall.pojo.SessExample.Criteria;

@Service
public class SessServiceImpl implements SessService {

	@Autowired
	private SessWriteMapper sessWriteMapper;

	@Autowired
	private SessReadMapper sessReadMapper;

	@Override
	public Integer insertSess(Sess sess) {
		sess.setExpiry(DateUtils.addDays(new Date(), 30));
		sess.setType(0);
		sess.setStatus(0);
		sess.setGmtCreate(new Date());
		sess.setGmtModify(new Date());
		sess.setLoginTime(new Date());
		int insert = sessWriteMapper.insertSelective(sess);
		return insert;
	}

	@Override
	public List<Sess> getListBySessionKey(String sessionKey, Integer commonOnlyKey) {
		if (StringUtils.isBlank(sessionKey)) {
			return null;
		}
		if (commonOnlyKey == null) {
			return null;
		}
		SessExample example = new SessExample();
		example.setOrderByClause(" id desc");
		Criteria criteria = example.createCriteria();
		criteria.andSesskeyEqualTo(sessionKey);
		criteria.andStatusEqualTo(0);
		criteria.andCommOnlyKeyEqualTo(commonOnlyKey);
		return sessReadMapper.selectByExample(example);
	}

	@Override
	public Integer updateSess(Sess sess) {
		sess.setExpiry(DateUtils.addDays(new Date(), 30));
		sess.setLoginTime(new Date());
		return this.sessWriteMapper.updateByPrimaryKeySelective(sess);
	}

	@Override
	public List<Sess> getListBySessionKeyAndUserId(String sessionKey, Long userId, Integer commonOnlyKey) {
		if (StringUtils.isBlank(sessionKey) || userId == null || userId <= 0 || commonOnlyKey == null) {
			return null;
		}
		SessExample example = new SessExample();
		Criteria criteria = example.createCriteria();
		criteria.andSesskeyEqualTo(sessionKey);
		criteria.andStatusEqualTo(0);
		criteria.andUidEqualTo(userId);
		criteria.andCommOnlyKeyEqualTo(commonOnlyKey);
		return sessReadMapper.selectByExample(example);
	}

	@Override
	public void deleteBySessionKeyAndUserId(String sessionKey, Long userId) {

	}

}
